package com.dongdongshop.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.dongdongshop.mapper.TbTypeTemplateMapper;
import com.dongdongshop.model.TbTypeTemplate;
import com.dongdongshop.model.TbTypeTemplateExample;
import com.dongdongshop.service.TypeService;
import com.dongdongshop.vo.TypeVO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class TypeServiceImpl implements TypeService {
    @Autowired
    private TbTypeTemplateMapper ttm;

    @Override
    public List<TypeVO> getAll(TypeVO typeVO) {
        TbTypeTemplateExample example = new TbTypeTemplateExample();
        TbTypeTemplateExample.Criteria criteria = example.createCriteria();
        if (StringUtils.isNotBlank(typeVO.getName())){
            criteria.andNameLike("%"+typeVO.getName()+"%");
        }
        List<TbTypeTemplate> tbTypeTemplates = ttm.selectByExample(example);
        List<TypeVO> collect = tbTypeTemplates.stream().map(vo ->{
            TypeVO TypeVO = new TypeVO();
            BeanUtils.copyProperties(vo, typeVO);
            return typeVO;
        }).collect(Collectors.toList());
        List<TypeVO> list = JSONObject.parseArray(JSONObject.toJSONString(tbTypeTemplates), TypeVO.class);
        return list;
    }

    @Override
    public void add(TypeVO typeVO) {
        TbTypeTemplate tbTypeTemplate = new TbTypeTemplate();
        BeanUtils.copyProperties(typeVO, tbTypeTemplate);
        ttm.insertSelective(tbTypeTemplate);
    }
}
